const config = require('@/config/qiniu');
const uuid = require('uuid');
const qiniu = require('qiniu');
const fs = require('fs'); // Node.js 文件系统模块
class UploadService {
  constructor() {
    this.mac = new qiniu.auth.digest.Mac(config.accessKey, config.secretKey);
    this.config = new qiniu.conf.Config();
    this.config.zone = qiniu.zone[config.zone];
    this.formUploader = new qiniu.form_up.FormUploader(this.config);
  }
  generateToken(key) {
    const putPolicy = new qiniu.rs.PutPolicy({
      scope: `${config.bucket}:${key}`,
      expires: 7200,
      returnBody: `{"key":"$(key)","url":"https://${config.origin}/$(key)"}`
    });
    console.log(`生成上传token: ${config.origin}/${key}`, config);
    return putPolicy.uploadToken(this.mac);
  }
  async uploadStream(filePath, originalName) {
    const ext = originalName.split('.').pop(); // 文件后缀
    const key = `articles/${uuid.v4()}.${ext}`; // 上传到七牛后保存的文件名
    const token = this.generateToken(key); // 生成上传凭证
    const stream = fs.createReadStream(filePath); // 读取本地文件

    return new Promise((resolve, reject) => {
      this.formUploader.putStream(
        token,
        key,
        stream,
        new qiniu.form_up.PutExtra(),
        (err, body) => {
          if (err) {
            stream.destroy();
            console.error('上传失败:', err);
            return reject(this.handleError(err));
          }
          console.log(body);
          resolve(body.url);
        }
      );
    });
  }
  handleError(err) {
    const codeMap = {
      'NetworkError': 503,
      'FileTooLarge': 413,
      'InvalidToken': 401
    };
    const code = codeMap[err.code] || 500;
    const error = new Error(err.message);
    error.status = code;
    return error;
  }
}


module.exports = new UploadService();
